﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Services
{
    public class WriteLog
    {
       /// <summary>
        /// 写错误日志
       /// </summary>
        /// <param name="errorMsg">错误日志内容</param>
       /// <param name="isException">是否是异常</param>
        public static void WriteLogs(string errorMsg, bool isException)
        {
            string logName = "";
            string folderName = "";
            if (isException)
            {
                folderName = HttpContext.Current.Server.MapPath("~/Exception/");
            }
            else
            {
                folderName = HttpContext.Current.Server.MapPath("~/Log/");
            }

            if (!Directory.Exists(folderName))
            {
                Directory.CreateDirectory(folderName);
            }
            if (isException)
            {
                logName = folderName + DateTime.Now.ToString("yyyyMMdd") + "Exception.txt";
            }
            else 
            {
                logName = folderName + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            }

            if (!File.Exists(logName))
            {
                File.Create(logName).Close();
            }


            using (FileStream fs = File.Open(logName, FileMode.Append, FileAccess.Write))
            {
                byte[] buffer = System.Text.Encoding.ASCII.GetBytes("\r\n" + DateTime.Now.ToString() + "\n" + errorMsg + "\r\n" + "----------------------------------------");
                fs.Write(buffer, 0, buffer.Length);
                fs.Dispose();
                fs.Close();
            }
        }

    }
}